<?php
/**
 * Created by PhpStorm.
 * User: liuyu
 * Date: 2018/11/19
 * Time: 11:19
 */

namespace App\Http\Controllers\Api\v1\Fortune;

use App\Http\Controllers\Api\BaseController;
use App\Tools\Astrolog\FortunesChange;
use App\Tools\HoroscopeData;
use App\Models\Api\AppLogicVersion;
use App\Models\Api\AwardUser;
use App\Models\Api\Orders;
use App\Models\Api\Recode;
use App\Models\Api\SystemLogicVersion;
use Illuminate\Http\Request;
use Cache;

class FortuneForYearController extends BaseController
{
    protected $orders_model;
    protected $award_user_model;
    protected $year_id;

    public function __construct()
    {
        //parent::__construct();

        $this->year_id = config('app.year_id');
        $this->orders_model = new Orders();
        $this->award_user_model = new AwardUser();
        $this->recodeModel = new Recode();
    }

    /**
     * @return \think\response\Json
     * @throws \app\common\lib\exception\ApiException
     */
    public function index(Request $request)
    {
        if (!$request->isMethod('get'))
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $uid = $request->uid;
        $rid = $request->input('rid');
        $year = $request->input('year');
        //当前查看的时间
        $now_time = strtotime($year . '-1');

        //日历显示时间范围
        $range_start = config('fortune.fortune_time_range')['year']['start'];
        $range_end = config('fortune.fortune_time_range')['year']['end'];
        //解锁状态
        $unlock_status = 0;
        $recode_info = [];
        $map = ['uid' => $uid, 'id' => $rid];
        //获取档案信息
        $recode_info = $this->recodeModel->getRecode($map);
    //     if(Cache::has('fortune_years_'. $uid.'_'.$rid,$year, 86400 * 365) && in_array($uid, config('vip'))){
    //             $start_time = date('Y', $now_time);
    //             $end_time = date('Y', strtotime(('2026-12-31')));
    //             $unlock_vip_time = prDates(['start' => $start_time, 'end' => $end_time, 'type' => '3']);
    //             $unlock_vip_times[] = $unlock_vip_time;
    //             $unlock_status = 2;
    //          if ($unlock_vip_times) {
    //             foreach ($unlock_vip_times as $k => $v) {
    //                 foreach ($v as $vv) {
    //                     $vip_time_range[] = $vv;
    //                 }
    //             }
    //         }
    //     } else {
    //     //TODO  是否为VIP用户判断，若为VIP用户，全部解锁且加入计算队列
    //     if (in_array($uid, config('vip')))
    //     {
    //             $start_time = date('Y', $now_time);
    //             $end_time = date('Y', strtotime(('2026-12-31')));
    //             $unlock_vip_time = prDates(['start' => $start_time, 'end' => $end_time, 'type' => '3']);
    //          //将运势加入队列运算
    //          // TODO 判断是否已经加入队列/已经计算完毕
    //          // 运势队列消费时需要的数据
    //          //$recode_infos[];
    //          $recode_infos[] = (new Recode())->getRecode(['uid' => $uid, 'id' => $rid]);
    //           $jobData = [
    //               'recode' =>$recode_infos,
    //               'start_time' => $unlock_vip_time,
    //               'type' => 'year',
    //           ];
    //           $unlock_vip_times[] = $unlock_vip_time;
    //         // 运势队列相关配置
    //           $fortune_job_setting = config('queue');
    //         //var_dump($recode_info);die;
    //          // VIP 用户加入立即计算队列中 否则 $fortune_job_setting['delay']
    //           queuePush($fortune_job_setting['fortune_task'],$jobData,$fortune_job_setting['fortune_queue'],0);
    //       //       VIP 用户更改为已解锁
    //         $unlock_status = 1;
    //         //$unlock_status = 2;
    //         Cache::set('fortune_years_' . $uid.'_'.$rid,$year, 86400 * 365);
    //          if ($unlock_vip_times) {
    //             foreach ($unlock_vip_times as $k => $v) {
    //                 foreach ($v as $vv) {
    //                     $vip_time_range[] = $vv;
    //                 }
    //             }
    //             $unlock_status = 2;
    //         }
    //     }
    // }

        // 先进行vip判断,不是再查看订单记录
//        if ($unlock_status === 100 && in_array($uid, config('vip')))
//        {
//            $time_range = prDates(['start' => $range_start, 'end' => $range_end, 'type' => 3]);
//
//
//            // TODO加入计算队列，VIP用户加入立即执行队列
//            $jobData = [
//                'recode' =>$recode_info,
//                'start_time' => $year,
//                'type' => 'year',
//            ];
////            // 运势队列相关配置
//            $fortune_job_setting = config('fortune_job');
////            // VIP 用户加入立即计算队列中 否则 $fortune_job_setting['delay']
//            queuePush($fortune_job_setting['task'],$jobData,$fortune_job_setting['queue'],0);
//            // 状态为计算中
////            $unlock_status = 1;

//            $unlock_status = 2;
//        } else
//        {
        //获取档案档案购买的订单
        $orders = $this->orders_model->fortune_orders(['uid' => $uid, 'rid' => $rid,'type'=>3]);
        //购买订单解锁的时间
        $unlock_time = [];
        $order_time = [];
        $unlock_time_range = [];

        if ($orders && !empty($orders))
        {
            foreach ($orders as $k => $v)
            {
                if ($v['type'] == 3)
                {
                    $extend = json_decode($v['extend'], true);
                    if (isset($extend['expire_time']) && $extend['expire_time'])
                    {
                        $v['expire_time'] = $extend['expire_time'];
                    }
                    $start_time = date('Y', $v['time']);
                    $end_time = date('Y', strtotime('-1 years',strtotime($v['expire_time'], $v['time'])));

                    $unlock_time['start_time'] = $start_time;
                    $unlock_time['end_time'] = $end_time;

                    // 获取当前档案已解锁的时间
                    $order_time [] = prDates([
                        'start' => $unlock_time['start_time'],
                        'end' => $unlock_time['end_time'],
                        'type' => 3,
                    ]);

                    if (strtotime($start_time . '-1') <= $now_time && $now_time <= strtotime($end_time . '-1'))
                    {
                        $unlock_status = 1;

                        if ($v['status'] == 4)
                        {
                            $unlock_status = 2;
                        }
                    }
                }
            }
            foreach ($order_time as $k => $v)
            {
                foreach ($v as $vv) $unlock_time_range[] = $vv;
            }
        }
        // 获取当前用户的档案id
        $selfId = $this->recodeModel->getSelfRecode(['uid' => $request->uid]);
        //获取中奖纪录
        $aorders = $this->award_user_model->get_award_fortune(['uid' => $request->uid, 'rid' => $rid, 'type' => 4,'self_id'=>$selfId]);
        //用户中奖解锁的时间
        $award_time = [];
        $unlock_award_times = [];
        $award_time_range = [];
        $vip_time_range =[];

        if ($aorders && !empty($aorders))
        {
            $date = date('Y', $now_time);
            foreach ($aorders as $k => $v)
            {
                $extend = json_decode($v['extend'], true);
                if (in_array($v['aid'], $this->year_id))
                {
                    $start_time = date('Y', $extend['award_time']);
                    $end_time = date('Y', strtotime('-0 years',strtotime($v['expire_time'], $extend['award_time'])));

                    $award_time['start_time'] = $start_time;
                    $award_time['end_time'] = $end_time;

                    // 获取当前档案已解锁的时间
                    $unlock_award_time = prDates([
                        'start' => $award_time['start_time'],
                        'end' => $award_time['end_time'],
                        'type' => 3,
                    ]);

                    if (in_array($date, $unlock_award_time) && $v['status'] == 1)
                    {
                        $unlock_status = 2;
                    } elseif (in_array($date, $unlock_award_time))
                    {
                        $unlock_status = 1;
                    }

                    $unlock_award_times[] = $unlock_award_time;
                }

            }
            if ($unlock_award_times)
            {
                foreach ($unlock_award_times as $k => $v)
                {
                    foreach ($v as $vv)
                    {
                        $award_time_range[] = $vv;
                    }
                }
            }
        }

        //合并时间
        //$time_range = array_merge($unlock_time_range, $award_time_range,$vip_time_range);
        $time_range = array_merge($unlock_time_range, $award_time_range);
        //时间去重
        $time_range = array_unique($time_range);
        //重新排序
        asort($time_range);
        //重新索引
        $time_range = array_values($time_range);
//        }

        //统计订单人数
//        $order_people_num = $this->orders_model->Unlock_people_num(['type' => 2]);
        $fortune_base_num = $this->orders_model->fortune_base(['type' => 2]);

        if ($unlock_status == 0)
        {
            $unlock_tips = [
                'title' => '年运解锁',
                'content' => '解锁当前运势，可查看你的'.$year.'年会发生什么，哪方面是今年的重点，它们是吉是凶，一整年又会有哪些起伏变化。（注意：解锁年运不包含月运）
一眼看穿365天，提前预知,早做安排。'
                ];
        } elseif ($unlock_status == 1)
        {
            $unlock_tips = [
                'title' => '年运计算等待中...',
                'content' => '由于年运的计算量较大,准了将在24小时内为您献上您所需要的年运。
小伙伴们耐心等待哦~',
            ];
        }
//        elseif ($unlock_status == 3)
//        {
//            $unlock_tips = [
//                'title' => '年运更新等待中...',
//                'content' => '由于年运正在重新计算中,准了将在24小时内为您献上您所需要的年运。',
//            ];
//        }
    else
        {
            $unlock_tips = [
                'title' => '你是vip用户',
                'content' => '欢迎你使用',
                ];
        }

        //更新逻辑数据定义
        $update_logic = [
            'title'=>'',
            'content'=>'',
            'status'=>0
        ];

        //用户计算成功后,获取年运信息及查询逻辑版本
        if ($unlock_status == 2)
        {
            //获取年运信息
            $fortune = (new FortunesChange())->init($recode_info, $year, 'year');
           //var_dump($fortune);die;
            //获取当前最新版本逻辑信息
            $SystemLogicModel = new SystemLogicVersion();
            $logic_data  = $SystemLogicModel->getVersion(['type'=>3]);
            //获取当前档案逻辑版本号
            $AppLogicModel = new AppLogicVersion();
            $user_logic = $AppLogicModel->getVersion(['rid'=>$rid,'type'=>3,'time'=>date('Y',$now_time)]);

            if ($user_logic)
            {
                //若查看的时间版本号不是最新,提示更新
                if ($logic_data['version'] && $user_logic < $logic_data['version'])
                {
                    $update_logic = [
                        'title' => $logic_data['title'],
                        'content' =>$logic_data['content'],
                        'status' => 1,
                    ];
                }
            }elseif(!$user_logic){
                $update_logic = [
                    'title' => $logic_data['title'],
                    'content' =>$logic_data['content'],
                    'status' => 1,
                ];
            }

            // 八字模块测试代码
//            $conclusion = (new Horoscope(['recode' => $recode_info,'advance'=>['year'=>$year]]))->yearConclusion();
        } else
        {
            // 未解锁||解锁中 返回空值
            $fortune = [
                'fortune_year_change' => [],
                'fortune_year_stage' => [],
                'fortune_year_summarize' => [
                'replace' => '你还没有解锁运势',
                'text' => ['请购买年运运势'],
            ],
                'fortune_year_outline' => [],
            ];
        }

        $data = [
            'time' => $time_range,
            'fortune_year_summarize' => $fortune['fortune_year_summarize'],
            'fortune_year_outline' => $fortune['fortune_year_outline'],
            'fortune_year_change' => $fortune['fortune_year_change'],
            'fortune_year_stage' => $fortune['fortune_year_stage'],
            'unlock_num' => intval($fortune_base_num),
            'unlock_status' => $unlock_status,
            'time_range' => [
                'start_time' => $range_start,
                'end_time' => $range_end,
            ],
            'update_logic' => $update_logic,
            'unlock_tips' => $unlock_tips,
        ];

        // 活动开关，默认关闭
        $config = '';
        $data['active_switch']=[
            'day_active'=>[
                'is_open'=>false,
                'icon'=>'',
                'banner'=>'',
                'target'=>'link',
                'link'=> '/web/fortune_year/active_details',//大礼包h5
            ],
            'month_active'=>[
                'is_open'=>false,
                'icon'=>'',
                'banner'=>'',
                'target'=>'link',
                'link'=>'/web/fortune_year/active_details',//大礼包h5
            ],
            'year_active'=>[
                'is_open'=>false,
                'icon'=>'',
                'banner'=>'',
                'target'=>'link',
                'link'=>'/web/fortune_year/active_details',//大礼包h5
            ]

        ];

        //若未解锁并在活动时间内，开启
        if (checktime() && $unlock_status == 0)
        {
            $data['active_switch']['day_active']['is_open']=false;
            $data['active_switch']['month_active']['is_open']=true;
            $data['active_switch']['year_active']['is_open']=true;
        }

        return show(config('code.success'), '加载成功', $data);

    }
}
